Repository navigation
feat(gemma4): port vMLX decode hot path - #55
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 461a0ab01c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let imageTokenId: Int | ||
| let visionSoftTokensPerImage: Int |
There was a problem hiding this comment.
Default optional Gemma4 config keys
For Gemma4 config files that omit image_token_id or vision_soft_tokens_per_image, this synthesized Decodable now treats both as required because they are non-optional let properties. The previous decoder defaulted the image token id to 258880 and the soft-token count to the vision tower's defaultOutputLength, so those bundles now fail to load before inference starts; add an explicit init(from:) that preserves those defaults.
Useful? React with 👍 / 👎.
| patchSize = try c.decodeIfPresent(Int.self, forKey: .patchSize) ?? 16 | ||
| maxSoftTokens = try c.decodeIfPresent(Int.self, forKey: .maxSoftTokens) ?? 280 | ||
| poolingKernelSize = try c.decodeIfPresent(Int.self, forKey: .poolingKernelSize) ?? 3 | ||
| imageSeqLength = try c.decodeIfPresent(Int.self, forKey: .imageSeqLength) ?? 280 |
There was a problem hiding this comment.
Read nested image processor settings
For the Gemma4 processor configs that place patch_size, pooling_kernel_size, max_soft_tokens, or image_seq_length under the nested image_processor object, these top-level-only lookups miss the real values and silently fall back to 16/3/280. That makes the processor resize images and expand <|image|> tokens with the wrong budget, which then either trips the maskedScatter feature/token count check or feeds the vision tower incorrectly; keep decoding the nested image_processor layout before falling back to top-level defaults.
Useful? React with 👍 / 👎.
| if nk.hasPrefix("language_model.") && !nk.hasPrefix("language_model.model.") { | ||
| nk = "language_model.model." + String(nk.dropFirst("language_model.".count)) | ||
| } |
There was a problem hiding this comment.
Keep lm_head weights outside model prefix
When a checkpoint contains language_model.lm_head.weight for an untied-embedding Gemma4 model, this remaps it to language_model.model.lm_head.weight, but lmHead is a sibling of model in G4LanguageModel. In that scenario the actual output head is not loaded (or the key is ignored), so logits come from an uninitialized head; exclude language_model.lm_head. from this prefix rewrite as the previous sanitizer did.
Useful? React with 👍 / 👎.
| let rp = cfg.ropeParameters[lk] ?? [:] | ||
| let rt = rp["rope_theta"]?.asFloat() ?? (isSliding ? 10000.0 : 1_000_000.0) | ||
| let prf = rp["partial_rotary_factor"]?.asFloat() ?? (isSliding ? 1.0 : 0.25) | ||
| self.rope = initializeRope(dims: max(1, Int(Float(hD) * prf)), base: rt, traditional: cfg.ropeTraditional, scalingConfig: nil, maxPositionEmbeddings: nil) |
There was a problem hiding this comment.
Preserve proportional RoPE for full attention
For Gemma4 full-attention layers where partial_rotary_factor is 0.25, passing dims: hD * prf with scalingConfig: nil turns this into default RoPE over the first 128 dims, pairing dimensions around 64 and using /128 frequencies. The previous VLM code and the MLXLLM text tower pass the full head dim plus the proportional scaling config, so pairs are taken across the 512-dim head and only the intended quarter is rotated; this mispositions every full-attention query/key and corrupts VLM logits.
Useful? React with 👍 / 👎.
| } else { | ||
| expanded.append(token) | ||
| } | ||
| if nk.contains(".switch_mlp.") { nk = nk.replacingOccurrences(of: ".switch_mlp.", with: ".experts.switch_glu.") } |
There was a problem hiding this comment.
Split fused MoE expert weights during sanitize
For Gemma4 26B-A4B checkpoints that store experts as .experts.gate_up_proj plus .experts.down_proj (the case handled by the previous sanitizer and by Gemma4TextModel.sanitize), this only rewrites .switch_mlp. names and then leaves the fused expert keys untouched. SwitchGLU expects experts.switch_glu.{gate,up,down}_proj.weight, so those expert weights are not loaded and the MoE block runs with initialized weights; keep the gate/up split and down-proj remap here.
Useful? React with 👍 / 👎.
| let f = sqrt(Float(maxP * ps * ps) / Float(w * h)) | ||
| let sm = config.poolingKernelSize * ps | ||
| var tH = Int(floor(f * Float(h) / Float(sm))) * sm; var tW = Int(floor(f * Float(w) / Float(sm))) * sm | ||
| if tH == 0 { tH = sm }; if tW == 0 { tW = sm } |
There was a problem hiding this comment.
Cap the resized long side after forcing a minimum side
For very wide or very tall images where one rounded target side becomes zero, this forces that side to one pooled patch (sm) but leaves the other side at the previously computed length. That can exceed the vision tower's maxPatches budget (e.g. a 1×10000 image), after which VisionTower clamps nReal but still reshapes the full position grid into [1, nReal, 2] and traps; recompute or cap the other side as the previous aspect-ratio helper did.
Useful? React with 👍 / 👎.
| targetW = sideMult | ||
| targetH = min(Int((h / w).rounded(.down)) * sideMult, maxSideLength) | ||
| var processedImage: LMInput.ProcessedImage? | ||
| if !input.images.isEmpty { |
There was a problem hiding this comment.
Process video inputs before applying the chat template
When UserInput.videos is non-empty, Qwen2VLMessageGenerator still emits video content in the prompt, but this processor only enters the image branch and never builds LMInput.ProcessedVideo or expands video placeholders into frame-token blocks. The prior Gemma4 processor sampled frames and attached video pixels, so video prompts now reach the model as bare special tokens with no visual embeddings.
Useful? React with 👍 / 👎.
| vocabSize = try c.decodeIfPresent(Int.self, forKey: .vocabSize) ?? 262144 | ||
| rmsNormEps = try c.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1e-6 | ||
| slidingWindow = try c.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 1024 | ||
| layerTypes = try c.decodeIfPresent([String].self, forKey: .layerTypes) ?? [] |
There was a problem hiding this comment.
Derive Gemma4 layer types when omitted
For Gemma4 text configs that omit layer_types, this now leaves the array empty; TextAttn and TextModel then fall back to sliding_attention for every layer. The previous decoder derived the sliding/full pattern from sliding_window_pattern, so these configs lose all full-attention layers and build the wrong cache/attention topology; generate the default pattern here instead of using [].
Useful? React with 👍 / 👎.
| // 258880 fallback covers tokenizers that don't expose `<|image|>` as | ||
| // an addable special token. | ||
| let imgId = tokenizer.convertTokenToId("<|image|>") ?? 258880 | ||
| var exp = [Int](); for t in tokens { if t == imgId { exp.append(contentsOf: Array(repeating: imgId, count: config.imageSeqLength)) } else { exp.append(t) } } |
There was a problem hiding this comment.
Insert BOI/EOI around expanded image tokens
For image prompts where the chat template emits a single <|image|> placeholder, this expansion repeats only the image token and drops the begin/end image delimiter tokens that the previous Gemma4 processor inserted. That changes the token sequence seen by the text tower for every image prompt and leaves the soft-token block without the delimiters the checkpoint expects; preserve the boiTokenId/eoiTokenId wrapping when expanding the placeholder.
Useful? React with 👍 / 👎.
| c.keys = keys | ||
| c.values = values | ||
| c.offsetArray = offsetArray |
There was a problem hiding this comment.
Deep-copy CompilableKVCache state
KVCache.copy() is documented and tested elsewhere as an independent deep copy, but this implementation assigns the same keys, values, and offsetArray objects into the copy. Updating the copied cache uses _updateInternal on those shared arrays, so checkpoint restore or speculative branches that copy a CompilableKVCache will also mutate the original cache; clone the valid state arrays as the other cache implementations do.
Useful? React with 👍 / 👎.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/mlx-swift-lm#
Verdict: COMMENT
Security — 1 finding(s)
- 🔵 [INFO]
Libraries/MLXLMCommon/DynamicSlice.swift:76-82— fatalError with user-controlled error code- Suggestion: Use proper error handling instead of fatalError with potentially user-controlled values
Performance — ✅ No issues found
Type_diligence — ✅ No issues found
Additive_complexity — ✅ No issues found
1 finding(s) total, 0 blocking. Verdict: COMMENT.
🤖 Automated review by Centaur · DAR-186
| &axesInt, | ||
| axesInt.count, | ||
| stream.ctx) | ||
| if rc != 0 { | ||
| fatalError("[dynamicSliceUpdate] mlx_slice_update_dynamic failed with rc=\(rc)") | ||
| } | ||
| return MLXArray(result) |
There was a problem hiding this comment.
🔵 [INFO] 🔒 fatalError with user-controlled error code
💡 Suggestion: Use proper error handling instead of fatalError with potentially user-controlled values
📊 Score: 3×2 = 6 · Category: command-injection
…, no left padding (Gemma 4 + GPT-OSS 20B) (#62) * feat(cbv2): frozen integration contracts + architecture + workstream specs for ContinuousBatchingV2 Per-request KV (no left padding, no shared frontier), rectangular [B,1] decode, attention owned by the layer cache (swappable v1 SDPA / v2 paged Metal backends), vLLM-style no-phase scheduler contract, prefix cache and provider bridge surfaces. Workstreams A-H build against this commit. * fix(cbv2): MLXFast is a namespace in MLX, not a module — drop import * feat(cbv2): core runtime — per-sequence KV storage + v1 attention dispatch WS-A deliverables for ContinuousBatchingV2: - CBv2FullSequenceKV: contiguous per-sequence buffer, doubling growth, O(n) slice-assign appends, temporal-order zero-copy views - CBv2WindowedSequenceKV: ring of exactly window slots, eviction keyed to absolute positions (recent end kept), temporal-order unwind with at most one two-slice concat, rollback with un-wrap (monotone oldestValidPosition so destroyed history is never re-exposed), pre-eviction history returned for multi-token chunks so early chunk tokens keep their full window - CBv2QuantizedSequenceKV: QuantizedKVCache-scheme triples (group 64, 4/8-bit), per-request dequantized views for v1 attention - CBv2ContiguousKVBackend: factory + truthful bytesInUse accounting, capacityExhausted admission, adopting-prefix path (windowed rows start at matched - window so absolute positions line up) - CBv2LayerCache: CBv2AttendingLayerCache + legacy KVCache (update traps), positionOffsets cached [B] int32 rebuilt from host ONLY on membership change, advanced on-device per step; innerState exposes lazy chains for the engine loop's asyncEval (DAR-325 hygiene) - CBv2AttentionV1: B==1 single SDPA, B>1 per-row split+concat (no masks — each row attends exactly its own KV), attendBorrowing for Gemma-4 KV-shared layers, mask mode a pure function of (L, kL, window) - AttentionUtils hook: v2 layer caches route through updateAndAttend at the top of attentionWithCacheUpdate - CONTRACT-ISSUES-A-core-runtime.md documents contract gaps + resolutions * feat(cbv2): Gemma4 + GPT-OSS v2 attention branch, LayerKindDerivation, newCacheV2 factories WS-F model adaptation for ContinuousBatchingV2: - LayerKindDerivation.swift: pure [CBv2LayerKind] derivation from config fields. Gemma 4: layer_types / pattern-5 fallback, trailing num_kv_shared_layers mapped to the last non-shared layer of the same type (mirrors previousKvs), asymmetric head dims (sliding headDim / full globalHeadDim), K-eq-V kv-head override, hasSinks=false. GPT-OSS: explicit layer_types or alternating sliding/full, sinks on every layer. - Gemma4Text.swift: v2 attention branch — when the layer cache is a CBv2AttendingLayerCache, route through updateAndAttend (own-KV layers) / attendBorrowing (KV-shared layers). Per-row RoPE offsets snapshotted from cache.positionOffsets BEFORE the update (graph-safe '+ 0' copy); KV-shared layers reuse the SOURCE layer's captured snapshot threaded through the trunk (invariant 1). Dual RoPE thetas, QK-norm and K-eq-V flow unchanged. Trunk builds no masks on the v2 path. Legacy paths (B=1 / old engine / MTP) untouched. - GPTOSS.swift: same v2 branch with sinks passed into updateAndAttend (denominator-only per contract). Sinks-activation probe refactored into sinksActiveResolved()/prepareSinksActivation(); newCacheV2 primes the Bool at load so the v2 step loop never performs the .item() host readback. - newCacheV2(makeLayerCache:) + cbv2LayerKinds on both models; the factory-closure shape (contract has no layer-cache constructor) is documented in docs/engine-v2/CONTRACT-ISSUES-F-models.md. * test: compile-gate stale Gemma4 VLM MTP spike suite The spike references the MLXVLM Gemma4 MTP surface (forwardForMTP, mtpConfiguration, rollbackSpeculativeCache, Gemma4Configuration .textConfiguration) that was removed when the vMLX decode hot path was ported (8a212b4). The file no longer compiles on main/feat/engine-v2 and blocks the entire MLXLMTests bundle from building, which blocks every CBv2 workstream's 'swift test --filter CBv2*' acceptance run. Gate the whole suite behind -DVLM_MTP_SPIKE_COMPILED (it was already env-gated at runtime via VLM_MTP_SPIKE); re-enable once the VLM MTP surface is restored. * feat(cbv2): WS-E sampling stage — vectorized logits pipeline, keyed sampler, incremental detok, stop holdback - LogitsPipelineV2: ordered [B,vocab] transforms (raw logprob capture, logit bias, repetition/frequency/presence penalties from incrementally scatter-added per-row count tensors, temperature, single-sort top-k/top-p/min-p); all per-row params as [B,1] tensors built at batch-membership change, zero per-row loops and zero host syncs in the step path - SamplerV2: all-greedy argMax fast path; mixed batches via exponential-noise Gumbel-max with per-row keys mixed from (seed, requestID, per-request step) so a row's stream never depends on batchmates or join time; where(greedy, argmax, sampled) merge - DetokenizerV2: per-request incremental detok with UTF-8 boundary holdback (trailing U+FFFD run) and bounded segment restarts - StopHoldback: longest-suffix stop-string holdback; earliest match truncates at match start, nothing past a stop is ever emitted - CONTRACT-ISSUES-E-sampling.md: topLogprobs=0 gap, CBv2SamplerRow carrier, nil-seed semantics, repetition-window population * test: compile-gate stale Gemma4 VLM MTP spike suite The spike references the MLXVLM Gemma4 MTP surface (forwardForMTP, mtpConfiguration, rollbackSpeculativeCache, Gemma4Configuration .textConfiguration) that was removed when the vMLX decode hot path was ported (8a212b4). The file no longer compiles on main/feat/engine-v2 and blocks the entire MLXLMTests bundle from building, which blocks every CBv2 workstream's 'swift test --filter CBv2*' acceptance run. Gate the whole suite behind -DVLM_MTP_SPIKE_COMPILED (it was already env-gated at runtime via VLM_MTP_SPIKE); re-enable once the VLM MTP surface is restored. * feat(cbv2): WS-D prefix cache — block-hash keyed, zero-copy donation BlockHasher.swift: SHA-256 chain hashing at fixed token blocks (default 256). Byte-compatible with the legacy checkpoint tier (computeBlockHash / omlx compute_block_hash) so SSD blocks interop later: with an empty salt the chain is byte-identical (verified against the legacy function and fixed independently-computed vectors). TB-007 tenant scoping: a non-empty cacheSalt is folded into the FIRST block hash only (length-prefixed, domain-tagged 'cbv2-salt-v1' section); the chain propagates it. PrefixCacheV2.swift: implements CBv2PrefixCache. - donate: zero-copy move of finished-request snapshot() arrays; indexes every whole-block boundary of the longest whole-block prefix (partial tail sliced lazily at lookup). Windowed and KV-sharing layers never enter full-history reuse (report 10 invariant 6) — their slots stay nil. Key contests prefer the longer entry (frees fully-shadowed duplicates) but never steal keys from pinned entries. - lookup: longest chain-hash match in whole blocks, capped at tokens.count - 1 (vLLM last-token rule); bumps LRU, pins the entry in-use, returns lazily-sliced per-layer snapshots (no eval anywhere). - evict(toFit:): LRU by monotonic access tick; in-use entries survive. - endAdoption(tokens:matched:) releases the pin (concrete-type method; the frozen protocol lacks a release hook — see docs/engine-v2/CONTRACT-ISSUES-D-prefix-cache.md). - requiredRecompute(layerKinds:matched:): max sliding window clamped to the match, 0 for all-full models — B's loop re-prefills that suffix. - NSLock-guarded; safe off the engine thread; bytesInUse truthful. Tests (CBv2PrefixCache*, 30 cases): fixed chain-hash vectors incl. salt separation + legacy byte-compat; donate/lookup roundtrip with matched whole blocks, last-token cap, longest-match among nested prefixes, and mid-block divergence miss; LRU eviction respecting in-use pins and byte budgets; pinned-entry key-repoint protection; windowed-policy recompute for Gemma-4-like (512) and GPT-OSS-like (128) layer sets; concurrency smoke over donate/lookup/evict. Mock CBv2SequenceKV only — no WS-A internals, no model weights. Note: running MLXLMTests needs mlx.metallib colocated with the test bundle (scripts/fetch-metallib.sh in d-inference builds it from libs/mlx-swift @ the resolved commit). * test(cbv2): WS-E sampling suite — pipeline order, penalties parity, batch-invariant RNG, detok, stop holdback 29 tests, no model weights required: - raw logprobs reflect untransformed logits with bias/penalties active - penalties parity vs scalar reference on random histories, including the incremental commit path and window eviction, and mid-flight rebuild == incremental state - vectorized top-k/top-p/min-p keep-sets vs scalar reference - determinism: same (seed, requestID) => identical tokens at B=1 and inside a B=4 mixed batch with greedy neighbors, across two runs; per-request step keying makes streams join-time invariant - greedy fast path bit-identical to argMax - DetokenizerV2: emoji/CJK/ZWJ sequences split across tokens, no mid-stream replacement chars, byte-exact totals, segment restarts - StopHoldback: stop split across 3 chunks, overlapping candidates, ambiguity release, earliest-match truncation, detok integration * test(cbv2): WS-F model tests — layer-kind derivation + v2 branch forward smoke 18 tests in 3 suites (swift test --filter CBv2Model), no model weights: - CBv2ModelLayerKindTests: exact [CBv2LayerKind] for the real Gemma-4 35-layer pattern-5 topology (shared tail 20 → sources 13/14, head dims 256/512), congruence with the trunk's previousKvs map, K-eq-V kv-head asymmetry (+ fallback without num_global_key_value_heads), GPT-OSS 24-layer alternating shape with sinks on every layer, explicit layer_types override. - CBv2ModelGemma4ForwardTests / CBv2ModelGPTOSSForwardTests: tiny-config random-weight models driven through the v2 branch with an in-file mock CBv2AttendingLayerCache (per integration protocol). Assert: 5-token prefill + 3 decode steps with pre-update offset snapshots [0,5,6,7]; offsets read exactly once per forward, strictly BEFORE updateAndAttend; KV-shared layers call attendBorrowing on the right source and NEVER read positionOffsets (they reuse the trunk-threaded source snapshot); zero makeMask calls (models build no masks on v2); zero legacy update() calls; multi-row decode with per-row offsets {5,2}/{6,2} (join-state batch-composition plumbing); GPT-OSS zero sinks ⇒ nil, active sinks ⇒ passed through with the Bool primed at newCacheV2. - Legacy regression: legacy newCache() paths still work (asserted), and the full existing Gemma4 suite passes (106 tests / 26 suites). Note: the branch base's Gemma4VLMMTPSpikeTests.swift does not compile (MLXVLM Gemma4 lacks forwardForMTP at this base); documented in docs/engine-v2/CONTRACT-ISSUES-F-models.md — file left untouched. * feat(cbv2): paged KV backend — slab pool, ring page tables, Metal paged-attention decode kernel WS-C deliverables 1-6 (docs/engine-v2/specs/C-paged-backend.md): - PagedKVPool: per-(kvHeads,headDim) slab groups, 16-token pages, O(1) free-list alloc/free with refcounts, reservation-based admission (update() cannot throw), truthful bytesInUse, CBv2KVQuantScheme hook with quantized-pages design TODO documented in the header - PagedSequenceKV: per-sequence page tables; windowed layers are page rings keyed to absolute positions (storage eviction, no masks) - pagedattention.metal + PagedAttentionKernel: flash-decode kernel via MLXFast.metalKernel — GQA-amortized KV reads (one threadgroup per (seq, kv head)), per-request lengths, ring/block tables, sliding window via start offsets, denominator-only sinks, optional softcap, head dims 64/128/256/512, fp16/fp32 pages (attribution: vLLM, mistral.rs, vllm-metal, MLX) - PagedLayerCache: kernel decode for any B, per-request SDPA fallback with pinned bool array masks for prefill chunks, attendBorrowing for Gemma-style KV-shared layers - PagedKVBackend: CBv2KVBackend impl, eligibility validation at build - PagedAttentionReference (composed fp32 parity oracle) and PagedBackendBenchmark (paged vs v1 per-row SDPA vs dense batch) - Package.swift: MLXFast product dep (contract imports it) and the .metal bundle resource * test: disable Gemma4VLMMTPSpikeTests (pre-existing build breakage) The env-gated VLM MTP spike references forwardForMTP / rollbackSpeculativeCache on the MLXVLM Gemma4 tower, whose Gemma4MTPTarget surface was removed in 8a212b4 (port vMLX decode hot path #55). The file no longer compiles and blocks the entire MLXLMTests target, so no test can run. Wrapped in #if false with a re-enable note; drop this commit at integration if another fix lands. * test(cbv2): core runtime unit tests + per-instance rebuild counter CBv2CoreTests (27 tests, 7 suites): - Full/Windowed/Quantized append/rollback/snapshot round-trips; growth by doubling preserves content; quantized group-size resolution - Windowed eviction at exact boundaries (window±1, wrap, multi-chunk crossings, oversize chunk), temporal order after wrap, rollback un-wrap (pre-wrap full recovery, post-wrap window shrink), non-zero initialOffset - ContiguousKVBackend: shapes + nil at KV-shared indices, truthful bytesInUse/release, capacityExhausted admission, invalid share source, quantized config, adopting-prefix (full-layer copy + windowed offset) - AttentionV1 parity: B=3 mixed lengths {7,130,950}, per-row batched decode output == solo decode (rtol 1e-4 fp16), full/windowed/windowed+sinks, GQA - float32 full-history reference: chunked prefill + decode outputs match exact causal-window masking semantics; sinks fold into denominator only; Gemma-style borrowed attention matches source KV without updating - positionOffsets under join/leave churn: device advance per step, host rebuild ONLY on membership change (per-instance counter) - 10-step decode loop performs zero host syncs and zero host rebuilds Adds CBv2LayerCache.positionOffsetsHostRebuilds (per-instance) so parallel test suites cannot interfere with the hygiene assertions. * fix(tests): single compile gate for stale Gemma4 VLM MTP spike (merge artifact) * test: disable Gemma4VLMMTPSpikeTests (pre-existing build breakage) The env-gated VLM MTP spike references forwardForMTP / rollbackSpeculativeCache on the MLXVLM Gemma4 tower, whose Gemma4MTPTarget surface was removed in 8a212b4 (port vMLX decode hot path #55). The file no longer compiles and blocks the entire MLXLMTests target, so no test can run. Wrapped in #if false with a re-enable note; drop this commit at integration if another fix lands. * test(cbv2): WS-C paged backend suites — pool/ring/kernel parity, invariance, greedy 200-step match - CBv2PagedBackendTests: slab-group accounting, atomic reservation admission, full-sequence roundtrips + rollback page frees, windowed ring wrap/eviction keyed to absolute positions, prefix adoption, fastForward placement, shared-layer nil states, eligibility errors - CBv2PagedKernelTests: decode kernel parity vs composed fp32 reference across head dims 64-512 / GQA / windows / sinks / softcap, bitwise batch-composition invariance, prefill chunk + sinks parity, KV-shared borrowing, positionOffsets, 200-step greedy token match (>=99.5%) - CBv2PagedBenchmarkTests: env-gated spec gate + always-on smoke - PagedLayerCache: cast sinks to the query dtype on the SDPA prefill path (MLX SDPA requires sink dtype to promote to the output dtype; fp32 sinks with fp16 activations trapped) - CONTRACT-ISSUES-C-paged-backend: windowed prefix adoption offsets, softcap plumbing, setRows, bytesReserved, shared-layer positionOffsets All 22 tests in 3 CBv2Paged suites pass. * test(cbv2): WS-G correctness harness — fixtures, invariance, parity, invariant suites - CBv2Fixtures: TinyTestModel (2-layer, full + sliding-window(16), optional GPT-OSS-style sinks, seeded weights, no downloads) implementing BOTH the legacy LanguageModel/KVCache path and the v2 path against the frozen contract; mock CBv2SequenceKV / CBv2AttendingLayerCache / CBv2KVBackend reference implementations; deterministic greedy v2 step-loop driver (per-request chunked prefill, rectangular [B,1] decode, join/leave). - CBv2InvarianceTests: batch-composition invariance — solo == batched with 1/2/3 neighbors, mid-stream join with churn, window crossing, sinks, 50-event churn storm; all token-exact over >=64 steps. Per-request-seed test marked pending integration (WS-E). - CBv2ParityTests: v2 B=1 vs legacy eager reference (Scheduler's exact fp16 cache substitution) token-exact UNCONDITIONALLY, and vs the full legacy Scheduler/EngineCore engine strictly on its eager path. Found a pre-existing legacy discrepancy: compiled B=1 decode diverges from the legacy engine's own eager path when the prompt already straddles a sliding window at compile time — documented in docs/engine-v2/CONTRACT-ISSUES-G-harness.md item 2 and downgraded to a skip (never a WS-G gate failure); DARKBLOOM_COMPILED_DECODE=0 gives strict engine parity, 7/7. - CBv2InvariantSuiteTests: executable encodings of report 10 §4 invariants 1-10 (positions, mask-free decode, update-order convention, rollback scrubbing, pinned attention path, window eviction boundaries, zero host syncs in the hot path, snapshot temporal order, sink eligibility + numerics, parity cross-ref). - Package.swift: exclude stale Gemma4VLMMTPSpikeTests.swift (broken at the engine-v2 branch base; blocks the whole test target). * feat(cbv2): WS-B scheduler + truthful soft admission SchedulerV2: vLLM-V1-style unified token-budget planner — no prefill/decode phases. RUNNING first in admission order (decode rows request exactly 1, prefills chunked), WAITING admitted under budget + maxConcurrentRequests, optimistic numComputedTokens advance at plan time with rollback, preemption backstop (lowest-priority/youngest victim, full restart with generated tokens kept, requeued at the front of its class; victim==requester stops the step, and no waiting admission in a preemption step). Pure synchronous bookkeeping: no MLX imports, fully unit-testable without weights. AdmissionV2: byte-ledger capacity oracle behind the WS-B-internal CBv2StepCapacity protocol. Submit-time canEverFit rejects what could never fit (worst case promptLen+maxTokens, window-capped per layer, KV-shared layers own nothing); step-time reserve is soft/optimistic behind a watermark with preemption as the backstop. Exposes CBv2CapacitySnapshot. * feat(cbv2): WS-B engine loop, bounded output streams, public EngineV2 EngineLoopV2: single serial engine queue doing graph-build + asyncEval only. Chained async decode (SGLang-MLX pattern): step N+1's [B,1] forward is built on step N's still-lazy sampled tokens and asyncEval'ed before the loop blocks on N's tokens, so stop detection is one step late by construction; a finished request wastes at most one slot-step and its KV tail is rolled back exactly 1. Chain breaks on any membership change (join possible, finish, cancel, pause, mid-prefill row). Mixed steps run a rectangular [B,1] decode batch plus per-request [1,chunk] prefills under one asyncEval. KV frees for rows that participated in an in-flight step are fenced behind that step's finalization (incl. the defensive chained-path preemption branch, which must NOT discard the victim's pending sample or its re-admission would deadlock). Per-request deadlines + step watchdog (120s/30s defaults) error-finish and flip the engine health signal; onStepWedge fires before streams are errored so wedge side effects are observable at wakeup. OutputStreamV2: per-request pull-based AsyncStream (unfolding — a push design would defeat backpressure via AsyncStream's unbounded buffer) with bounded buffer; crossing capacity pauses exactly that request's scheduling (slot retained), draining below the low watermark resumes it; events are never dropped. The unfolding/onCancel closures capture the stream strongly: the engine drops its reference when it enqueues the terminal event, so the consumer-held sequence is what keeps undrained events alive (a weak capture raced deallocation and dropped tail events). Consumer cancellation maps to request cancellation via onAbandoned. EngineV2: thin CBv2Engine wiring (scheduler + admission + loop + sampler + detokenizer stubs until WS-E). submit rejects what could never fit (capacityExhausted), degenerate requests finish immediately with a uniform event surface, cancel is O(1) at the next step boundary, capacity() reads the gauges published after every step, shutdown drains gracefully. * test(cbv2): WS-B scheduler/loop/stream/admission suites + contract issues 41 tests, no model weights anywhere (scripted next-token=(input+1)%vocab model, mock KV backend/capacity oracle/detokenizer): - CBv2SchedulerTests (16): budget invariants, chunked prefill progress and multi-partial-prefill budget splits, priority + FCFS, maxWaiting rejection, preemption victim selection/requeue-front/same-plan refund/self-preempt stop/no-admission-during-preemption, optimistic-advance rollback, cancel in every state, chain-eligibility membership rules, pause/resume, and Poisson simulations (roomy: zero preemptions; tight: preempts and still drains). - CBv2SchedulerLoopTests (14): exact scripted sequences, chained decode one step late, stop token with <=1 wasted step + KV tail rollback(1), stop string via detokenizer holdback, batch-composition invariance, cancel, backpressure pausing exactly the slow stream, preemption end-to-end with seamless victim resume, deadline error-finish, watchdog wedge signal, degenerate submissions, oversized rejection, shutdown drain. - CBv2SchedulerStreamTests (5): ordering, single pause/resume transitions, terminal idempotence, parked-consumer wakeup, abandonment on cancellation. - CBv2SchedulerAdmissionTests (6): window-capped + KV-sharing-aware estimates, worst-case canEverFit, watermark reserve, unreserve/release symmetry, windowed plateau, snapshot soft/hard truth. Also documents the contract gaps hit (layer-cache factory, sampler and detokenizer surfaces, release-fencing vs in-flight lazy graphs, non-capacity rejections, scheduler<->admission capacity hook) with the conforming shapes chosen, for resolution at integration. * test(cbv2): WS-G benchmark harness + test plan - benchmarks/CBv2Benchmark.swift (executable target CBv2Benchmark): B in {1,2,4} x prompt in {64,2048} greedy decode matrix reporting TPS/request, aggregate TPS, TTFT p50, ITL p50/p99, and the decode-step CPU-vs-GPU split at the asyncEval boundary. Tiny mode is CI-runnable (seeded 2-layer full+window model, per-request KV, per-row SDPA, [B,1] decode — no downloads); --model <path> measures the legacy engine on real weights as the baseline until EngineV2 merges (integration adds the CBv2Engine binding). Requires mlx.metallib colocated with the binary (same as every executable in this package). - docs/engine-v2/TESTPLAN.md: report 10 §4 invariants 1-11 and report 12 items 4/5/18 mapped to concrete test names, gate invocations (incl. the DARKBLOOM_COMPILED_DECODE=0 strict parity run), and the integration re-pointing checklist for the harness mocks. * perf(cbv2): two-pass flash-decoding paged-attention kernel — B>=2 gate passes across the matrix Rework the decode kernel from one threadgroup per (row, kv head) — which left the GPU idle at low batch (8 threadgroups at B=1, 9.5 GB/s at 16k) — to vLLM-V2/MLX-2pass style split-K: - pass A: one threadgroup per (row, kv head, 256-token partition) computes unnormalized partials + (m, l) meta in fp32 (GQA heads share the K/V read; up to 8 simdgroups per threadgroup) - pass B: one simdgroup per (row, query head) merges partials with a global online-softmax merge; sinks fold into the denominator only - partition count derives from each row's OWN attended length, and excess threadgroups launched for longer batchmates return early into slots that are never read, so outputs stay bitwise batch-composition invariant (invariance test now spans the multi-partition boundary) - maxpart comes from threadgroups_per_grid.z (MLX injects _shape params for inputs only); params/sinks device arrays cached per layer across steps Gate (benchmarks/cbv2-paged-attention.md, M4 Max): beats per-row SDPA at every B>=2 cell (up to 2.7x at B=8) and at B=1 16k; B=1 short-context misses the 15% bar by a constant ~0.2-0.3 ms/step of dispatch overhead (two custom-kernel dispatches + seqinfo upload vs one fused SDPA primitive) — follow-up documented in the benchmark file. All 22 CBv2Paged tests pass. * contract(cbv2): reconcile integration contract — setRows, fastForward, softcap config, Sendable engine, stepsExecuted, endAdoption, bytesReserved - CBv2AttendingLayerCache.setRows(_:) is the canonical row-binding method (C§3/B§1) - CBv2SequenceKV.fastForward(to:) + ONE windowed-adoption semantics: engine slices matched prefix by cbv2RequiredRecompute to a uniform offset; both backends position every row there and the engine replays the trailing tokens (C§1/A§3) - attention-logit softcap as construction-time layer-cache config on the contiguous backend too (CBv2LayerCache(attentionSoftcap:), composed fp32 path); verified Gemma 4 uses only final-logit softcap — no model change needed (C§2) - CBv2Engine: Sendable adopted; EngineV2 @unchecked Sendable justified (H) - CBv2CapacitySnapshot.stepsExecuted (monotonic, additive default) published per step (H) - CBv2KVBackend.bytesReserved (default bytesInUse) + release-fencing contract text (C§4/B§4) - CBv2PrefixCache.endAdoption(tokens:matched:) requirement (default no-op) (D§1) - cbv2RequiredRecompute free function in the contract; PrefixCacheV2 delegates (D§3) - CBv2SchedulerConfig.enablePrefixCache (default false) - PrefixCacheV2.donate(tokens:snapshots:layerKinds:) + materializeOnDonate for the paged backend's recyclable slab views - docs/engine-v2/CONTRACT-DECISIONS.md records every decision * feat(cbv2): wire the seams — real sampler/detokenizer/caches/models/prefix-cache run together in EngineV2 - CBv2DefaultSampler (LogitsPipelineV2 + SamplerV2) conforms to CBv2StepSampler and is EngineV2's default; protocol gains pendingSampledTokens + lazy rowContext so reconfiguration on membership change is exact (chained in-flight tokens folded in on-device; no host syncs). CBv2GreedySampler stays as the deterministic test stub. - CBv2TextDetokenizerFactory: DetokenizerV2 (UTF-8 holdback) + StopHoldback (stop-string holdback) behind CBv2IncrementalDetokenizer; flush-tail stop completion still truncates. - CBv2LayerCacheBank: persistent per-layer caches behind CBv2LayerCacheProvider; row-identity fingerprint means setRows (host positionOffsets rebuild) only on membership change — chained decode does zero host rebuilds. - CBv2SteppableLanguageModelAdapter: any LanguageModel (Gemma 4 / GPT-OSS v2 branches) as CBv2SteppableModel; PagedLayerCache gains the trap-style KVCache conformance so it travels through [KVCache] model plumbing like CBv2LayerCache. - Prefix cache wired end to end: lookup + slicing on the submit thread, adoption on the engine thread at enqueue (uniform-offset semantics, capacity reserved, numComputedTokens fast-forwarded, pin always balanced), donation on natural finish OFF the engine queue (snapshots graph-built on the engine thread, release hops back), usage.prefixCacheHitTokens reported. Gated by CBv2SchedulerConfig.enablePrefixCache + injected instance; off by default. - WS-G harness re-pointed at the real CBv2SteppableModel (mirror retired); the XCTSkip'd per-request-seed invariance test now runs the real EngineV2 + CBv2DefaultSampler and passes (solo == batched, token-exact). swift test --filter CBv2: 194 green (3 skips = documented pre-existing legacy compiled-decode divergence, CONTRACT-ISSUES-G §2). * test(cbv2): true end-to-end suite — real EngineV2 assembly on both backends Tests/MLXLMTests/CBv2EndToEndTests.swift constructs the production EngineV2 from the real subsystems (TinyTestModel as CBv2SteppableModel + ContiguousKVBackend / PagedKVBackend (fp16 pages, Metal decode kernel) + CBv2LayerCacheBank + CBv2DefaultSampler + CBv2TextDetokenizerFactory + PrefixCacheV2) and asserts, per backend: (i) 3 concurrent streams, mixed prompt lengths: correct rendered text and token-exact batch invariance vs solo runs; stepsExecuted published (ii) stop string completed mid-stream truncates text exactly at match start (iii) cancel mid-decode frees the slot; batchmates finish token-exact vs solo (iv) second submit of the same prompt hits the prefix cache (usage.prefixCacheHitTokens == whole-block match − windowed recompute) with identical greedy output; paged run uses materializeOnDonate (v) paged variant skips gracefully if the backend rejects the hardware Fix shaken out by the suite: the donation block captured the loop weakly, so a donation landing after engine teardown skipped the deferred backend.release and leaked paged pages (deinit assertion). The block now retains the loop until the donation + release complete (no cycle; obligation-scoped). TinyTestModel.make gains a headDim override (paged kernel supports 64/128/256/512). swift test --filter CBv2: 202 tests, 0 failures (3 documented legacy compiled-decode skips). * fix(cbv2): Sendable annotations for cross-queue handoffs - CBv2PrefixCache: AnyObject, Sendable — implementations are thread-safe by design (lookup on submit threads, donation off the engine queue) - CBv2PrefixAdoption: @unchecked Sendable (immutable single-consumer handoff, submit thread -> engine queue) - CBv2Handoff box for engine-owned state/snapshots crossing donation/engine queues (safe by ownership transfer); snapshots built into an immutable local Silences the new #SendableClosureCaptures warnings introduced by the prefix wiring; no behavior change. CBv2 suites: 202 green. * fix(cbv2): materializeOnDonate defaults to true — safe-by-default paged donation Review finding: PagedKVBackend + a default-config PrefixCacheV2 could index donated views over slab pages that get recycled after the donor's release. The device materialization (not a host readback; donation already runs off the engine step thread) now defaults ON; contiguous deployments may opt out. CBv2 suites: 202 green. * fix(cbv2): borrowed windowed attention attends pre-eviction views under chunked prefill Contiguous backend: a KV-borrowing layer (Gemma-4 cross-layer sharing) over a sliding-window source attended snapshot() — the POST-eviction ring (<= window entries) — while the source layer's own update() deliberately returns PRE-eviction history + chunk (window-1+n entries) so the chunk's earliest queries see their full window. With prompt > window and chunked prefill, the first query of every chunk >= 2 attended 1 key instead of window (on Gemma-4, 16 of 20 KV-shared layers are sliding(512)). Fix mirrors the paged backend's exact-by-construction design: - CBv2WindowedSequenceKV retains the last multi-token update()'s returned views as a step-scoped borrowableViews() (cleared on decode update and rollback; bounded to one extra window buffer between updates). - CBv2AttentionV1.attendBorrowing selects views as a pure function of L (pinned-path discipline): chunk borrows (L > 1) attend the pre-eviction views through the existing kL > window array-mask path; decode borrows (L == 1) keep mask-free snapshot semantics. Regression fixture: TinyTestModel gains a Gemma-4-shaped KV-sharing variant (sliding source + borrowing layer + storage-owning full layer DOWNSTREAM so wrong borrowed attention corrupts persistent KV, not just discarded prefill logits). New CBv2KVSharingParityTests assert chunked prefill token-exact vs an unchunked B=1 reference on BOTH backends, plus the windowed borrow-view mechanism. Verified the contiguous parity test fails without the fix. * fix(cbv2): fingerprint paged device tables by pool serial, not heap address PagedLayerCache.deviceTables cached device block tables keyed by (ObjectIdentifier, tableVersion). ObjectIdentifier is a heap address that can be recycled after a finished request's row deallocates, and the LIFO free list gives a replacement row the same page ids and tableVersion trajectory — a stale fingerprint hit would let the decode kernel attend a finished request's cached tables (cross-request read). PagedKVPool now issues a monotonic UInt64 row serial to every PagedSequenceKV; the fingerprint is (serial, tableVersion), so identity reuse is structurally impossible. Added a tablesRebuildCount hook and a regression test that releases a row, allocates an identical-geometry replacement (same page ids, same tableVersion, different serial), and asserts the tables are rebuilt. * fix(cbv2): canEverFit judges feasibility against the watermark-adjusted capacity AdmissionV2.canEverFit compared the worst case against FULL bytesCapacity while reserve enforces capacity - watermark. A request whose worst case landed in (0.95*cap, cap] was admitted, hit the reservation wall on its final tokens, self-preempted, restarted, and livelocked until its deadline. Feasibility now uses admissibleBytesCapacity (capacity - watermark), the same ceiling reserve enforces; EngineV2's capacityExhausted payload reports it too. Regression tests: unit (95 tokens admits+reserves, 96..100 rejected by BOTH canEverFit and reserve) and engine-level (watermark-band request rejected at submit with capacityExhausted). * feat(cbv2): structural guard — paged backend requires materializing prefix caches Follow-up to the safe-by-default materializeOnDonate flip (25688bc): the pairing rule is now enforced structurally instead of by convention. CBv2KVBackend gains requiresMaterializedSnapshots (default false; true for PagedKVBackend, whose donated snapshot views reference recyclable shared slabs). EngineV2 construction preconditions on the pairing via an internal testable validator: an ACTIVE PrefixCacheV2 with materializeOnDonate:false paired with such a backend is a construction-time failure, not a silent prefix-cache corruption. Custom CBv2PrefixCache impls own the obligation themselves (documented on the contract). Test covers the violation matrix and a real safe construction. * fix(cbv2): suppress the stop token's text in the final delta (OpenAI behavior) The final delta before a stop-token .stop finish carried the stop token's detokenized text; OpenAI-compatible streams exclude it. finalize now checks stop membership before the detokenizer push: the stop token's text is never emitted (and the detokenizer's held-back text stays intact for the finish flush), while the raw delta tokens still carry the id and usage.completionTokens still counts it. Documented the delta contract in CBv2Contracts: text is authoritative user-facing content; tokens are raw sampled ids that may include the stop token / extend past a stop-string match. Regression tests on both backends assert text ends exactly before the stop token with usage unchanged. * fix(cbv2): drop stale prefix-hit credit when an adopted request is preempted Preemption discards the adopted KV and recomputes the full prompt from scratch, but prefixHitTokens kept the adoption-time entry, so usage.prefixCacheHitTokens over-credited at finish. Both preemption paths (handlePreemptions and the chained-path defensive preemption) now remove the entry. Regression test: scripted prefix cache + capacity-forced preemption; the preempted-adopted request finishes with prefixCacheHitTokens == 0 while a non-preempted adopted batchmate keeps its true credit, and every lookup pin is balanced by exactly one endAdoption. Verified the test fails without the fix (reports 2). * fix(cbv2): bound shutdown by a timeout when the engine queue is wedged drain() enqueued its completion on the engine queue, so a wedged queue (a step blocked inside an eval) hung shutdown() forever. Drain continuations are now resume-once waiters raced against a shutdownTimeout timer (new CBv2EngineLoopConfig knob, default 10s) on the watchdog queue: on timeout, live streams are force-finished with .error, live requests are marked for cancellation (cleaned up if the loop ever resumes — same discipline as watchdogTick), and shutdown returns; the wedged step may still be executing, documented on drain()/shutdown(). Regression test wedges the scripted model for 3s with shutdownTimeout 0.3s and asserts shutdown returns promptly with the stream error-finished. * fix(cbv2): backend drift/trap hardening + review nit batch - PagedLayerCache now gates sinks on kind.hasSinks (mirroring CBv2AttentionV1) in both updateAndAttend and attendBorrowing; a sink-free layer ignores a mistakenly passed array. Regression test with deterministic position-coded inputs (global-RNG-free: Swift Testing runs suites in parallel) fails without the gate. - attentionWithCacheUpdate: documented that the CBv2 hook DISCARDS the mask parameter and passes sinks nil for non-adapted models; a debug assertion now rejects custom array masks on that path (.none/.causal are subsumed by v2's position-derived masks). - CBv2PrefixCache.lookup doc: spelled out the pin-balance obligation (every hit balanced by exactly one endAdoption on every path); the endAdoption default no-op stays so non-pinning conformers keep compiling. - donationQueue: documented why donation evals may run concurrently with engine-step evals over the same slabs (MLX array versioning pins graph-built snapshot views; release-after-donate keeps donor pages out of the pool until the donation lands). - PrefixCacheV2 donation dedup now re-registers missing intermediate block keys (lost when a shorter pinned entry owning them is later evicted); test proves the 1-block prefix hits again after a dedup donation. - CBv2EndToEndTests: softened the prefix-cache 'exact by construction' claim — cross-shape SDPA determinism is empirical, not guaranteed. * feat(cbv2): per-request prefix-cache salt (TB-007, D§2 un-deferred) CBv2Request gains cacheSalt (additive, default nil). Salted CBv2PrefixCache overloads (lookup/donate/endAdoption with cacheSalt:) default to the unsalted methods, so existing conformers are untouched; PrefixCacheV2 implements them by swapping the request salt into the first block hash (the chain propagates the scope), falling back to the cache-level salt when nil — nil-salt hash vectors stay byte-identical. The engine threads the salt end to end: submit-time lookup, adoption pin release on every path, and donation (CBv2DonationIntent carries the donor's salt so entries land in the donor's scope). Tests: cross-salt isolation in both directions (nil included), salted pin balance, nil-salt byte-compat, cache-level-salt fallback, plus an end-to-end engine round trip (tenantA donates; tenantB and nil miss; tenantA hits token-exact). * fix(cbv2): skip prefix-cache donation for quantized KV (lossy snapshots) Defect found while adding quantized donation coverage: MLX affine quantization is NOT idempotent — the kernel snaps each group's scale to its dominant edge (scale = edge / round(edge / scale)), so re-quantizing a DEQUANTIZED snapshot lands on a different grid. A quantized donate → adopt round trip therefore drifts the adopted KV by up to ~1 quantization step vs a cold run (measured: 0.26 max abs at 4-bit, 0.016 at 8-bit on fp16 normals), compounding with every donate→adopt generation. Greedy runs on the tiny fixture happened to stay token-exact, but that is argmax margin, not an invariant. Per the deferred-item directive, donation is now skipped explicitly: CBv2SequenceKV.snapshotIsLossless (additive, default true) reports value-exactness; CBv2QuantizedSequenceKV returns false; the engine's donationIntent and PrefixCacheV2's state-based donate refuse lossy cacheable rows. Adopting full-precision donations INTO a quantized backend remains legal (single quantization, same as a cold prefill). Tests: requantization-drift canaries (4/8-bit — fail if MLX ever becomes idempotent, signalling the skip can be lifted), engine-level skip on all-full-attention and mixed-windowed TinyTestModel variants (cache stays empty, repeat prompts miss, output token-exact vs no-cache), and a full-precision control round trip on the new fullAttentionOnly fixture. * feat(cbv2): emit per-token logprobs end-to-end (E§1 follow-up) CBv2Event.delta's logprobs field is now populated. When any row of a sample call requests topLogprobs > 0, CBv2DefaultSampler gathers the chosen-token logprob and top-K alternatives from the RAW pre-transform log_softmax (raw-logprobs-first rule) as graph nodes only, hands them to the loop via the new CBv2StepSampler.takeStepLogprobs() (additive, default nil), and the loop rides them on the step's asyncEval. They are materialized at the finalize boundary — the same one-step-late readback where sampled tokens are read for stop detection — so the chained decode path gains no host syncs. Batches with no logprobs rows build zero extra graph nodes (pinned by pipeline/sampler counters). Tests (scripted distinct-logits table model through the real engine): chosen logprob and 3 ordered alternatives vs scalar log_softmax references across chained decode; raw-first under a sampling-steering logit bias; zero-work counters for topLogprobs == 0; batch invariance of a logprobs row next to a non-logprobs row. * feat(bench): BenchCBv2 real-weights validation driver + first Gemma4-26B/GPT-OSS reports Correctness smoke (greedy, v2 contiguous): B=1 sanity with EOS stop, batch-composition invariance (solo / B=3 burst / mid-stream join, token-exact), chunked-prefill invariance (512-chunked vs unchunked), with topLogprobs divergence diagnostics and a solo-repeat determinism precondition. Perf matrix: legacy (Scheduler->EngineCore, compiled decode per process env) vs EngineV2 contiguous/paged at B=1/2/4 with mixed 100/500/1500-token prompts. Loads local checkpoints via LLMModelFactory.shared explicitly: the registry tries the VLM factory first and text-only Gemma-4 checkpoints carry a vision tower, which would select the MLXVLM Gemma4 (no CBv2 hooks). Driver-side paged preflight mirrors the part kernel's NSG=1 threadgroup-memory floor because an oversized config traps in Metal instead of throwing (Gemma-4 global layers: headDim 512, GQA 8 -> 32832 B > 32768 B). * fix(cbv2): model the paged kernel's threadgroup-memory budget in eligibility Gemma-4 global layers (headDim 512, GQA 8) passed the head-dim-only eligibility check but need (GQA*D + NSG*GQA*(D+2))*4 = 32,832 B of threadgroup memory even at NSG=1 — 64 B over Metal's 32,768 B cap — so the first paged dispatch killed the process with an uncatchable "Threadgroup memory size (32832) exceeds the maximum (32768)" fatal. - PagedAttentionKernel now models the part kernel's threadgroup allocations exactly (partThreadgroupBytes, threadgroupMemoryLimit, mergeRecordMetaFloats — named constants mirroring the shader, with a single-source-of-truth comment in pagedattention.metal and a drift guard test over the generated bodies). simdgroupsPerThreadgroup returns nil instead of falling through to NSG=1 when nothing fits. - ineligibilityReason(headDim:gqa:) is the kernel-level static eligibility check; PagedKVBackend.init routes every layer (including KV-shared ones) through it and throws backendIneligible before any dispatch. One over-budget layer makes the whole model ineligible. - BenchCBv2RealModel drops its local preflight copy of the formula and relies on the backend check. - Header note: the paged kernel is correct but unoptimized on real-model shapes (~100x slower than contiguous on GPT-OSS-20B, ~2.0 s/token GPU-side; requests error via the 30 s step watchdog); it stays non-default behind explicit construction, optimization is follow-up, and the post-watchdog teardown SIGSEGV is a known issue to investigate with the perf work. Tests: CBv2PagedEligibility suite — budget math vs shader constants, largest-fit NSG selection, Gemma-4 d512/gqa8 refusal with a threadgroup memory reason, mixed-model refusal, d128/gqa8 and d64/gqa8+sinks still eligible. * feat(cbv2): compiled [B,1] decode — bucket ladder, per-request compiled state, engine integration Whole-step compiled decode for ContinuousBatchingV2 (plan Phase 1): - Compiled/CompiledDecodeConfigV2: config (buckets {1,2,4}, kvCapacity, DARKBLOOM_CBV2_COMPILED kill switch) + CBv2CompiledSteppableModel marker. - Compiled/CompiledLaneStateV2: per-bucket lane offset counters (compile input+output state, advanced in-graph AFTER the forward so every read observes pre-update RoPE offsets) and per-window oldest-valid statics (input-only state) with host mirrors for self-healing rebinds. - Compiled/CompiledLayerCacheV2: overflow-bin attending cache — fixed-shape per-lane buffers (the request rows' OWN arrays), dynamicSliceUpdate writes with offset-as-data, boolean masks (modular token-index masks for sliding windows, RECENT end kept, fastForward/rollback residue excluded via oldest-valid bounds), per-lane SDPA (batch-composition invariance by construction), Gemma-style borrow against the source's post-update state. - Compiled/CompiledDecodeV2: bucket ladder tracing at warmup (never on the request path), dtype probe + model-side host-sync priming off the traced region, lane bind/self-heal by object identity + host offset mirrors, inert scratch lanes for padded buckets with capacity-threshold recycling, eager fallback for any unsupported shape, stats. - Row-state bridge: CBv2FullSequenceKV.compiledStorage (identity-preserving pad to bucket capacity) / CBv2WindowedSequenceKV.compiledStorage (shared ring) + noteCompiledAdvance host mirrors. - EngineLoopV2: decodeLogits tries compiled first for chained and mixed pure-decode batches; eager provider composition force-invalidated after compiled steps (stale positionOffsets hazard); warmup runs on the engine queue before the first step. EngineV2 wires CBv2CompiledDecodeConfig (default on for eligible models) and exposes compiledDecodeStats. * feat(bench): decode-step phase profiler + host-contention stamping Investigating the reported v2-vs-legacy eager decode gap on gpt-oss-20b-MXFP4-Q8 (report showed v2 26.2 TPS vs legacy 35.2 at B=1). The gap does not exist in the engine: it was host contention during the original benchmark run. On an uncontended host the SAME binary measures legacy eager 79.3 TPS and v2 106.6 TPS at B=1 (v2 +34%); with 14 CPU-hog threads running, legacy lands at exactly 35.2 TPS and v2 at 34.0 — reproducing the report's numbers and proving the artifact. Eager decode is CPU-bound (graph build + asyncEval submit), so ambient CPU load directly divides TPS; compiled decode (GPU-bound, ~10 ms/step) is barely affected, which is why the same session's legacy-compiled run still hit 99 TPS. Tooling so this class of error cannot recur silently: - CBv2StepProfiler: opt-in (CBV2_STEP_PROFILE=1 or programmatic) phase recorder; disabled cost is one static Bool branch per site. - EngineLoopV2: phase timers on the chained-decode hot path (boundary, forward graph build, sampler build, asyncEval submit, readback wait, detok push, stream emit, step wall). - Legacy GenerationBatch.step / Scheduler.processGenResponses / EngineCore: matching timers (forward build, asyncEval submit, readback wait, step wall, detok, scheduler-step wall). - BenchCBv2 --mode profile: warms up, then runs the B=1 cell per engine with the profiler on and emits a per-phase decomposition table. - BenchCBv2 report header now stamps 1m load average + darkbloom process presence and flags HOST CONTENDED when load > cores/2, with a startup warning. Clean-host B=1 decomposition (gpt-oss-20b, 128 tokens): v2 step wall p50 9.2 ms (asyncEval submit 7.9, forward build 1.2, readback 0.03, detok 0.08) vs legacy 12.4 ms (submit 7.4, forward build 5.0, readback 0.01, detok 0.09). v2's remaining ceiling is MLX submit cost, addressed by the separate compiled-decode workstream. 236 CBv2 tests green (160 XCTest + 76 swift-testing). * feat(cbv2): paged-decode root-cause profiler (slab sweep, layer sweep, GPT-OSS emulation) Wall-clock ablations isolating why real-model paged decode is ~100x slower than contiguous despite a healthy 1-layer microbenchmark: - slab-size sweep (1 layer): flat — no O(slab) term at one layer - layer sweep (2 GiB pool, B=1, ctx 512): write-only stays linear+cheap (0.33 -> 4.6 ms, zero step-peak memory) but write+dispatch explodes (0.49 -> 236 ms with 8 GiB step-peak) — every layer's slab slice-update after an attention-kernel read degrades into a full-slab copy - 24-layer GPT-OSS emulation at the real 16 GiB pool: 25.5 s/step B=1, 2.0 s/step B=4 vs 4.7/45.5 ms for per-row contiguous SDPA — reproduces the benchmarks/reports watchdog failures without model weights Root cause (vendored MLX source): gpu::eval retains every op's INPUT data shared_ptrs in the command-buffer completion handler (donated outputs are erased, kernel-read inputs are not), so after a custom kernel reads the slab, the next slice-update fails is_donatable (data.use_count > 1) and copies the whole slab. 24 layers x K+V x 8 GiB = ~370 GiB of copies per decoded token. * test(cbv2): compiled decode parity + fallback suites; lane release on retire - CBv2CompiledDecodeTests: token-exact compiled-vs-eager EngineV2 parity across solo / B=2 / padded bucket (B=3→4, inert scratch lane) / full bucket / window crossing / sinks / KV-sharing / seeded sampling / mid-stream join churn (pinned to solo baselines); capacity-overflow mid-request fallback (compiled→eager transition + eager growth past the compiled padding); oversized-allocation full-eager; quantized rows never compiled; scratch-lane recycling across requests; stable chained batches rebind lanes only on membership (DAR-325 class) with exactly one warmup trace per bucket; unit numerics pinning of the overflow-bin masks vs CBv2LayerCache incl. ring wrap and fast-forwarded (prefix-adopted) rows against poisoned unwritten slots. - CBv2CompiledLayerCache.clearLane + CBv2CompiledDecode.forgetRows: retired requests' padded buffers are dropped from idle bucket bindings at every KV release site (finish/cancel/preemption) instead of lingering until the next rebind. - TinyTestModel opts into CBv2CompiledSteppableModel, so the existing EngineV2 suites (E2E, scheduler-loop with contiguous rows) exercise the compiled path with the default-on config; full --filter CBv2 run: 176 tests, 0 failures. * docs(engine-v2): paged-attention kernel research — hardware table, reference-kernel budgets, 100x root cause, d512 design space * bench(cbv2): v2-compiled engine variant + compiled-parity correctness gates - BenchCBv2 gains the v2-compiled engine (contiguous backend + compiled decode ON; plain v2 cells stay explicitly eager for a clean comparison). Compiled cells absorb their per-engine trace with a warm request before measuring and report per-bucket warmup seconds, compiled step counts, rebinds, scratch resets, and fallback reasons. - Correctness mode adds compiled-parity (eager solo vs compiled solo, near-tie divergences classified as kernel numerics via the logprob gap) and compiled-invariance (compiled solo vs compiled B=3 burst — per-lane attention must make neighbors invisible). * fix(cbv2): per-LAYER compiled KV dtypes — GPT-OSS mixes fp32 (Yarn full-attention) and bf16 (sliding) caches A single probed dtype made every real GPT-OSS bind fail (bind_failed layer1: full-attention rows cache float32 K/V because YarnRoPE computes in fp32, sliding rows cache bfloat16) so the compiled path silently never engaged on real weights. The warmup probe now records each storage-owning layer's actual KV dtype from the primed forward and scratch/bind use the per-layer dtype, keeping every trace signature exact. Bind refusals now carry a full diagnostic (layer, kind, offset, dtype vs expected) in the fallback stats — this is what surfaced the bug. * chore(cbv2): bound bind-failure stat-key cardinality (drop per-step offsets from fallback keys) * perf(cbv2): in-place paged KV writes — fused decode write + bulk write kernel (fixes the ~100x real-model slowdown) The slabs are now STABLE buffers written in place by Metal kernels, never versioned through MLX slice updates. Root cause of the field failure: MLX's gpu::eval retains every op's INPUT data handles until the command buffer completes, so a slice-update following any attention kernel read of the slab failed donation and copied the entire slab — 23 layers x {K,V} x 8 GiB = ~370 GiB of GPU copies per decoded token on GPT-OSS-20B at the 16 GiB pool (docs/engine-v2/kernel-research.md §3). - Decode: pass A gains knew/vnew inputs and per-row {writePage, writeSlot} seqinfo fields; the threadgroup owning a row's last partition writes the step's K/V tile in place (device-scope barrier) before attending. Kills 2 slice-update dispatches per layer per step. - Prefill/adoption: new paged_kv_write kernel scatters [KVH, N, D] tiles at host-computed physical slots in ONE dispatch per chunk. - Ordering: MLX encoders are concurrent with hazard tracking at declared-buffer granularity, so in-place writes are invisible to it. Every write (bulk or fused) advances a per-group WRITE FENCE ([1] int32); every slab reader (part kernel via the wfence input, gathers via the page-index add) consumes the latest fence — scheduling order and memory barriers by construction, and raw write()+decode sequences (parity fixtures, KV-borrowing) are correct without engine help. Measured (M4 Max, PagedDecodeProfiler): - layer sweep, 2 GiB pool, B=1 ctx 512: 24 layers 236.4 -> 11.4 ms/step (step-peak transient memory 8 GiB -> 0) - 24-layer GPT-OSS emulation, 16 GiB pool: B=1 25,470 -> 13.6 ms/step, B=4 1,999 -> 14.3 ms/step — level with per-row contiguous SDPA - all 36 paged suite tests + 81 CBv2 tests pass (incl. kernel parity, batch-composition invariance, 200-step greedy match, borrowing) * fix(cbv2): review round 1 — thread-safe compiled stats, lane cleanup on bind failure, fail-safe oldest-valid guard; adoption + single-token parity tests - CBv2CompiledDecode.stats is now a lock-protected snapshot (providers poll it from heartbeat threads while the engine mutates per step). - A failed bindRow clears the whole lane (placeholder buffers + counter reset): a half-updated lane mixed the new row's and the previous binding's buffers, and the previous row's forgetRows could no longer match it — its padded buffers could be retained indefinitely. - laneInfo: equal-window oldest-valid disagreement now falls back to eager (guard) instead of a release-stripped assert. - Tests: single-token prompt parity (fresh rows allocate compiled-shape storage mid-step) and prefix-cache donation→adoption round trip under compiled decode (snapshot slicing of padded buffers + fastForward'ed windowed lanes), hit accounting compared across modes. - Bench: --kv-capacity flag for per-model overflow-bin sizing experiments. * feat(cbv2): head-split paged kernel — d512/GQA-8 (Gemma-4 global layers) now eligible Pass A gains an HPT (heads per threadgroup) template parameter: a kv head's GQA query heads split across GQA/HPT threadgroups, so neither the threadgroup-memory surfaces (q_smem[HPT*D], red_smem[NSG*HPT*(D+2)]) nor the per-thread accumulator (HPT*D/32 floats, capped at 32) scale with the full GQA factor at large head dims. The split is per-HEAD: no head's summation order changes, so batch-composition invariance and per-row determinism are untouched. Fleet d64/d128 shapes keep HPT == GQA — the kernel is bit-identical for them. - headsPerThreadgroup: largest divisor of GQA within the 32-float acc budget (d512 -> 2, d256 -> 4 at GQA 8; d64/d128 unchanged) - partThreadgroupBytes now models the split; Gemma-4 global layers (d512, GQA 8, the old 32,832 B > 32,768 B field fatal) run HPT=2 at NSG=4 in 20,544 B; every supported head dim is eligible at any fleet GQA - grid gains the split factor: (KVH * GQA/HPT * 32*NSG, B, parts); the fused decode write is executed by every split threadgroup of the last partition (idempotent duplicate, each self-sufficient after its own barrier) - CBv2PagedEligibilityTests updated to model the split (headSplitModel, budget anchors, Gemma-4 shape constructs); parity matrix gains the real Gemma-4-26B global shape (d512, kvh 2, qh 16) and a windowed d512 case — 82 CBv2 tests pass * bench(cbv2): real-weights validation of the paged kernel fixes — GPT-OSS + Gemma-4 reports Same-run v2 vs v2-paged on M4 Max (BenchCBv2, 128 steps): - GPT-OSS-20B MXFP4-Q8: paged B=1 89.9 TPS vs 99.5 contiguous (0.90x); B=4 aggregate 86.5 vs 84.4 — paged beats contiguous. Previously every paged request died on the 30 s step watchdog (~0.5 tok/s). - Gemma-4-26B-A4B 8bit: FIRST paged run ever (global d512/GQA-8 layers were statically ineligible before the head split). B=1 66.8 vs 67.2 (0.99x); B=4 aggregate 59.3 vs 56.3 — paged beats contiguous. - All correctness gates pass; the teardown SIGSEGV (followed watchdog-errored runs) no longer reproduces. - kernel-research.md gains the before/after outcome section. * bench(cbv2): record post-kernel-opt paged-attention microbenchmark run Paged beats v1 per-row SDPA at every B >= 2 cell (up to 4x at B=8) and at B=1/16K ctx. The B=1 ctx=512 gate cell remains over the 1.15x bound (1.29x, fixed two-dispatch overhead at tiny contexts) — it was already 1.36x at the recorded 2026-07-01 baseline, so this is an improvement, not a regression; real-model B=1 is 0.90x of contiguous. * fix(cbv2): review round 2 (Codex P1/P2) — admission padding reserve + softcap veto P1: compiled padding could silently exceed the KV byte budget. Full- attention rows pad to kvCapacity slots (4 bytes/element worst case — the fp32 Yarn layers) and scratch lanes are invisible to token admission entirely. CBv2CompiledDecode.build now computes the worst-case padding reserve (concurrent rows' full-layer padding + scratch lanes' padding and rings, derived from the bucket ladder) and EngineV2 carves it out of the AdmissionV2 ledger; a budget the reserve would halve refuses to build the compiled path instead of over-committing. Heartbeat capacity remains the hardware truth. Warmup now also releases each bucket's throwaway scratch right after its trace, bounding the transient warmup footprint to one bucket's lanes. P2: attention-softcap mirroring was unenforced — an eager bank built with CBv2LayerCache(attentionSoftcap:) plus a default compiled config would silently drop the softcap from compiled numerics. EngineV2 now reads the bank's uniform construction-time softcap and propagates it into the compiled config, whose build() refuses non-nil softcaps. Tests: exact reserve arithmetic + tight-budget refusal + admission ledger reduction; softcapped-bank veto. Full CBv2: 180 tests, 0 failures. * fix(cbv2): race-free fused decode write (single writer, tile read from inputs) + review doc fixes Review follow-ups (Codex + independent Claude review of the kernel-opt diff): - Eliminate the head-split write race the Codex review flagged: only the hgroup-0 threadgroup of a row's last partition stores the K/V tile, and NO threadgroup reads that slot from the slab within the dispatch — the newest position is loaded from the knew/vnew INPUTS instead (bit-identical bytes, numerics unchanged). No duplicate writes, no read-after-racy-write; later dispatches remain ordered by the fence chain / step-graph edges. The pass-A barrier drops back to mem_threadgroup (nothing device-scope is consumed in-dispatch). - Stale prose swept: threadgroup-budget block now says HPT (the GQA version is the exact bug that fataled Gemma-4 global layers), PTOK doc says 256, structure comment describes the head-group KV reuse, adoption comment says in-place bulk-write kernel (not slice updates), gather/attendableViews explain the real retention hazard (in-place mutation of recycled pages, not donation), kernel-research.md §2/§3.4/ §4 updated (head-split row, single-writer decode, C landed / B is a follow-up). - Document the RECYCLE INVARIANT at PagedSequenceKV.releaseStorage: pages must only be freed after the row's last consuming step is host-synced; a release-without-host-sync fast path would race. 82 CBv2 tests pass. * docs(bench): regenerate GPT-OSS reports on a near-idle host + decode-step profile The first GPT-OSS report (committed in 2dc34fa) was taken while the host was heavily loaded (parallel builds during active development), which divides eager decode TPS — eager decode is CPU-bound on graph build + asyncEval submit. It showed legacy 35.2 / v2 26.2 TPS at B=1; the same binary on a near-idle host measures legacy 77-79 / v2 96-107. A 14-thread CPU-hog reproduction lands legacy at exactly 35.2 TPS and v2 at 34.0, confirming the artifact. There is no v2-vs-legacy eager gap: v2 is ~25-35% faster at B=1 and leads aggregate TPS at B=2/4. - main: correctness all PASS; legacy 77.2 / v2 96.1 TPS at B=1; v2-paged no longer traps (a0ae73b) but crawls — separate workstream. - legacy-compiled: 103.3 TPS at B=1 (was 99.4 — also mildly depressed in the original run). - decode-profile (new): per-phase decomposition of the B=1 decode step; v2 step wall p50 9.7 ms (asyncEval submit 8.3, forward graph build 1.2, readback 0.04, detok 0.08) vs legacy 12.5 ms (submit 7.4, forward build 5.1). Both engines are submit-bound in eager mode. Headers now stamp the 1m load average at start; residual load from the back-to-back benchmark session itself (11-19 on 16 cores, no external processes) is flagged conservatively as CONTENDED. Gemma-4-26b-a4b-8bit spot check on the same session: v2 77.5 vs legacy 63.4 TPS at B=1; aggregate 75.9 vs 65.3 at B=4 — no regression. * fix(cbv2): softcap veto is a CBv2LayerCacheProvider protocol obligation — fail-safe on no-claim providers (Codex P2 round 3) * bench(cbv2): composed-final engine matrix on 255b223 — GPT-OSS 20B + Gemma-4-26B-A4B, 5 engines x B=1/2/4 Final authoritative BenchCBv2 perf matrix for the composed engine-v2 tip (compiled decode + kernel-opt in-place slab writes + d512 head-split): one process per engine config, 120s cool-downs, correctness last, per-run contention + memory stamps. Correctness: all 5 checks PASS on both models (b1-sanity, invariance, chunked-prefill, compiled-parity, compiled-invariance). Methodology note: back-to-back sessions that began with the correctness suite showed a decaying cross-process degradation (v2 eager B=1 deterministically halved ~105 -> ~50 TPS in 3/3 such sessions, decaying over subsequent configs) while isolated perf chains reproduced clean numbers 15/15; hence correctness-last ordering and wide gaps. * fix(cbv2): reject duplicate ids, per-layer admission bytes, reserving backend, B>1 attention guard (PR#62 review) Addresses four Codex PR#62 findings in independent subsystems: - finding 6 (SchedulerV2): duplicate CBv2RequestID silently clobbered `byID` while the stale record kept its queue slot. `enqueue` now rejects a still-live id with `CBv2SchedulerError.duplicateRequestID`; reusable once finished. - finding 5 (AdmissionV2): admission assumed a flat 2 bytes/element, so GPT-OSS fp32 full-attention K/V was ~2x under-charged. Config gains an optional per-layer element-bytes table (built from probed cache dtypes via `Config.elementBytes(forDTypes:)`); estimation is now per layer. - finding 4 (CBv2ContiguousKVBackend): rows report byteCount==0 until first update, so same-step admissions could collectively exceed bytesCapacity. Admission now reserves the estimated bytes atomically per row (released with the row, trued up to actual allocation); adds truthful `bytesReserved`. - finding 7 (attentionWithCacheUpdate): the legacy CBv2 compatibility path applies scalar RoPE via KVCache.offset (max row offset), mis-rotating shorter rows at B>1. It now fails loudly for B>1 while keeping B==1 exact. Tests: duplicate-while-waiting/running + reuse-after-finish; mixed fp32/bf16 element-bytes table; N same-step admissions cannot exceed capacity + reservation true-up; B==1 allowed / B>1 rejected diagnostic. * fix(cbv2): evaluate offset chain per step, detok off engine thread, honor early cancels (PR#62 review) Three Codex PR#62 findings in the engine loop (EngineLoopV2): - finding 1 (DAR-325 class): updateAndAttend advances cachedPositionOffsets lazily (+ L), but the per-step asyncEval set only held sampled/logit handles, so the eager offset chain accumulated unevaluated across long decode chains (the documented innerState collapse was never actually wired). The step now submits the eager layer caches' inner state (offset chain + KV buffers) into asyncEval every eager step, on both the chained and genera…
Summary
Results
79.5 tok/sonmlx-community/gemma-4-26b-a4b-it-8bit(M4 Max, B=1, 128 generated tokens).mlx-vlmon the same machine/model was 69.7 TPS.provider-swift swift build --build-testspassed;CompilableKVCacheTestspassed 4/4.Before
After
Notes
MLXHardwareInfoavoids colliding with ProviderCore's existingHardwareInfotype.Verification
mlx-swiftruntime and reproduced77-79 TPS.79.5 tok/s.